import React, { useState, useEffect } from 'react';
import { Trash2, Edit, Search, Calendar, Filter as FilterIcon, RefreshCw } from 'lucide-react';
//import CameraMappingManager from '../components/ChannelTable';
import VideoPlayer from '../components/VideoPlayer';
import API_CONFIG from '../utils/apiConfig';

const VideoAdminPage = ({ user }) => {
  const [videos, setVideos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  // 用于视频播放的状态
  const [selectedVideo, setSelectedVideo] = useState(null);
  // 添加分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [videosPerPage] = useState(10);
  // 添加筛选相关状态
  const [channelFilter, setChannelFilter] = useState('all');
  // 修改时间筛选状态为年月日
  const [selectedYear, setSelectedYear] = useState('');
  const [selectedMonth, setSelectedMonth] = useState('');
  const [selectedDay, setSelectedDay] = useState('');

  // 在现有状态变量后面添加跳转页码状态
  const [jumpPage, setJumpPage] = useState('');
  // 获取视频列表
  useEffect(() => {
    const fetchVideos = async () => {
      try {
        setLoading(true);
        const response = await API_CONFIG.fetch('videos'); // Changed port 3001
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        setVideos(data);
        setError(null);
      } catch (err) {
        setError('无法加载视频数据');
        console.error('Error fetching videos:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchVideos();
  }, []);

  // 获取所有唯一的通道号
  const uniqueChannels = [...new Set(videos.map(video => video.channel_number))].sort();

  // 获取视频中的所有年份
  const getUniqueYears = () => {
    const years = [...new Set(videos.map(video => new Date(video.start_time).getFullYear()))];
    return years.sort((a, b) => b - a); // 降序排列
  };

  // 获取月份选项（1-12）
  const getMonths = () => {
    return Array.from({ length: 12 }, (_, i) => i + 1);
  };

  // 获取日期选项（根据选择的年月动态生成）
  const getDays = () => {
    if (!selectedYear || !selectedMonth) {
      return Array.from({ length: 31 }, (_, i) => i + 1); // 默认显示31天
    }
    
    const daysInMonth = new Date(parseInt(selectedYear), parseInt(selectedMonth), 0).getDate();
    return Array.from({ length: daysInMonth }, (_, i) => i + 1);
  };

  // 过滤视频 - 增强版
  const filteredVideos = videos.filter(video => {
    // 文本搜索过滤
    const textMatch = video.point_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                     video.filename.toLowerCase().includes(searchTerm.toLowerCase());
    
    // 时间筛选 - 按年月日
    let timeMatch = true;
    const videoDate = new Date(video.start_time);
    
    if (selectedYear) {
      timeMatch = timeMatch && videoDate.getFullYear() === parseInt(selectedYear);
    }
    
    if (selectedMonth) {
      timeMatch = timeMatch && (videoDate.getMonth() + 1) === parseInt(selectedMonth);
    }
    
    if (selectedDay) {
      timeMatch = timeMatch && videoDate.getDate() === parseInt(selectedDay);
    }
    
    // 通道筛选
    const channelMatch = channelFilter === 'all' || video.channel_number.toString() === channelFilter;
    
    return textMatch && timeMatch && channelMatch;
  });

  // 处理筛选变化
  const handleFilterChange = () => {
    setCurrentPage(1); // 筛选时重置到第一页
  };

  // 重置所有筛选
  const resetFilters = () => {
    setSelectedYear('');
    setSelectedMonth('');
    setSelectedDay('');
    setChannelFilter('all');
    setSearchTerm('');
    setCurrentPage(1);
  };

  // 处理年份变化，同时重置月份和日期
  const handleYearChange = (year) => {
    setSelectedYear(year);
    setSelectedMonth('');
    setSelectedDay('');
    handleFilterChange();
  };

  // 处理月份变化，同时重置日期
  const handleMonthChange = (month) => {
    setSelectedMonth(month);
    setSelectedDay('');
    handleFilterChange();
  };

  // 修改鼠标悬停相关的状态和处理函数
  const [showPopup, setShowPopup] = useState(false);
  
  // 处理视频卡片点击 - 直接播放视频
  const handleVideoClick = (video) => {
    setSelectedVideo(video);
  };
  
  // 处理关闭视频播放器
  const handleClosePlayer = () => {
    setSelectedVideo(null);
  };

  // 删除视频
  const handleDeleteVideo = async (videoId) => {
    if (!window.confirm('确定要删除这个视频吗？此操作不可恢复。')) {
      return;
    }
    
    try {
      const url = API_CONFIG.getURL('videos') + `/${videoId}`;
      const response = await fetch(url, { // Changed port from 3001 to 3002
        method: 'DELETE',
        headers: {
          'x-user-role': user.role
        }
      });
      
      if (response.ok) {
        // 从本地状态中移除已删除的视频
        setVideos(videos.filter(video => video.id !== videoId));
        alert('视频删除成功');
      } else {
        const errorData = await response.json();
        alert(errorData.error || '删除视频失败');
      }
    } catch (error) {
      console.error('删除视频错误:', error);
      alert('删除视频失败');
    }
  };

  // 计算当前页的视频
  const indexOfLastVideo = currentPage * videosPerPage;
  const indexOfFirstVideo = indexOfLastVideo - videosPerPage;
  const currentVideos = filteredVideos.slice(indexOfFirstVideo, indexOfLastVideo);

  // 计算总页数
  const totalPages = Math.ceil(filteredVideos.length / videosPerPage);

  // 处理页面改变
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 重置搜索时的页码
  const handleSearchChange = (e) => {
    setSearchTerm(e.target.value);
    setCurrentPage(1); // 搜索时重置到第一页
  };

  // 添加跳转到指定页面的处理函数
  const handleJumpToPage = () => {
    const page = parseInt(jumpPage);
    if (page >= 1 && page <= totalPages) {
      handlePageChange(page);
      setJumpPage('');
    } else {
      alert(`请输入有效的页码 (1-${totalPages})`);
    }
  };
  
  // 处理跳转输入框的键盘事件
  const handleJumpPageKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleJumpToPage();
    }
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return (
      <div className="error">
        <h3>{error}</h3>
        <p>请检查网络连接或稍后重试</p>
      </div>
    );
  }

  return (
    <div className="video-admin-page"> {/* 修改为独立类名 */}
      <div className="video-admin-content"> {/* 修改为独立类名 */}
        {/* 筛选控件区域 */}
        <div className="video-admin-controls-stats-container"> {/* 修改类名 */}
          <div className="video-filter-controls-container"> {/* 修改类名 */}
            <div className="video-filter-controls"> {/* 修改类名 */}
              {/* 添加搜索框到筛选控件区域 */}
              <div className="filter-group">
                <div className="filter-label-wrapper">
                  <Search className="filter-label-icon" size={16} />
                  <label className="filter-label">搜索视频:</label>
                </div>
                <input
                  type="text"
                  placeholder="输入视频名称或文件名..."
                  value={searchTerm}
                  onChange={handleSearchChange}
                  className="filter-select search-input"
                  style={{ width: '250px', minWidth: '200px' }} // 添加最小宽度以防止过度缩小
                />
              </div>
              
              {/* 其他筛选控件保持不变 */}
              <div className="filter-group">
                <div className="filter-label-wrapper">
                  <Calendar className="filter-label-icon" size={16} />
                  <label className="filter-label">时间筛选:</label>
                </div>
                <div className="date-filter">
                  {/* 年份选择器 */}
                  <select 
                    value={selectedYear}
                    onChange={(e) => handleYearChange(e.target.value)}
                    className="filter-select"
                  >
                    <option value="">选择年份</option>
                    {getUniqueYears().map(year => (
                      <option key={year} value={year}>{year}</option>
                    ))}
                  </select>
                  
                  {/* 月份选择器 */}
                  <select 
                    value={selectedMonth}
                    onChange={(e) => handleMonthChange(e.target.value)}
                    disabled={!selectedYear}
                    className="filter-select"
                  >
                    <option value="">选择月份</option>
                    {getMonths().map(month => (
                      <option key={month} value={month}>{month}月</option>
                    ))}
                  </select>
                  
                  {/* 日期选择器 */}
                  <select 
                    value={selectedDay}
                    onChange={(e) => {
                      setSelectedDay(e.target.value);
                      handleFilterChange();
                    }}
                    disabled={!selectedMonth}
                    className="filter-select"
                  >
                    <option value="">选择日期</option>
                    {getDays().map(day => (
                      <option key={day} value={day}>{day}日</option>
                    ))}
                  </select>
                </div>
              </div>
              
              <div className="filter-group">
                <div className="filter-label-wrapper">
                  <FilterIcon className="filter-label-icon" size={16} />
                  <label className="filter-label">通道筛选:</label>
                </div>
                <select 
                  value={channelFilter} 
                  onChange={(e) => {
                    setChannelFilter(e.target.value);
                    handleFilterChange();
                  }}
                  className="filter-select channel-filter"
                >
                  <option value="all">所有通道</option>
                  {uniqueChannels.map(channel => (
                    <option key={channel} value={channel}>通道 {channel}</option>
                  ))}
                </select>
              </div>
              
              <div className="filter-actions">
                <button 
                  onClick={resetFilters}
                  className="reset-filters-btn"
                  title="重置所有筛选条件"
                >
                  <RefreshCw size={16} className="reset-icon" />
                  重置
                </button>
              </div>
            </div>
          </div>
          <div className="video-stats">
          <div className="stat-card">
            <h3>总视频数</h3>
            <span className="stat-number">{videos.length}</span>
          </div>
          <div className="stat-card">
            <h3>筛选结果</h3>
            <span className="stat-number">{filteredVideos.length}</span>
          </div>
          <div className="stat-card">
            <h3>时间筛选</h3>
            <span className="stat-number">
              {selectedYear && selectedMonth && selectedDay ? 
                `${selectedYear}年${selectedMonth}月${selectedDay}日` :
                selectedYear && selectedMonth ? 
                `${selectedYear}年${selectedMonth}月` :
                selectedYear ? 
                `${selectedYear}年` : '全部'}
            </span>
          </div>
          <div className="stat-card">
            <h3>通道筛选</h3>
            <span className="stat-number">
              {channelFilter === 'all' ? '全部' : `通道 ${channelFilter}`}
            </span>
          </div>
        </div>

        {/* 使用当前页的视频列表，而不是所有筛选后的视频 */}
        <div className="video-admin-grid">
          {currentVideos.map((video, index) => (
            <div 
              key={video.id} 
              className="video-admin-card"
              onClick={() => handleVideoClick(video)}
              style={{ position: 'relative', zIndex: 1, cursor: 'pointer' }}
            >
              <div className="video-admin-info">
                <h4>{video.point_name}通道{video.channel_number}</h4>
                <p className="video-filename">{video.filename}</p>
                <p className="video-time">{video.start_time}</p>
                <p className="video-objects">检测对象: {video.object_labels.join('、')}</p>
              </div>
              
              <div className="video-admin-actions">
                <button
                  className="admin-btn delete-btn"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeleteVideo(video.id);
                  }}
                  title="删除视频"
                >
                  <Trash2 size={16} />
                  删除
                </button>
                <button
                  className="admin-btn edit-btn"
                  onClick={(e) => {
                    e.stopPropagation();
                    alert('编辑功能待实现');
                  }}
                  title="编辑视频信息"
                >
                  <Edit size={16} />
                  编辑
                </button>
              </div>
            </div>
          ))}
        </div>

        {/* 添加分页控件 */}
        {filteredVideos.length > videosPerPage && (
          <div className="pagination">
            <button 
              onClick={() => handlePageChange(1)} 
              disabled={currentPage === 1}
              className="pagination-btn"
            >
              首页
            </button>
            <button 
              onClick={() => handlePageChange(currentPage - 1)} 
              disabled={currentPage === 1}
              className="pagination-btn"
            >
              上一页
            </button>
            
            {/* 显示页码 */}
            {Array.from({ length: totalPages }, (_, index) => index + 1)
              .filter(page => {
                // 只显示当前页附近的页码，避免页码过多
                if (totalPages <= 7) return true;
                if (page === 1 || page === totalPages) return true;
                return Math.abs(page - currentPage) <= 2;
              })
              .map((page, i, arr) => (
                <React.Fragment key={page}>
                  {/* 添加省略号 */}
                  {i > 0 && arr[i] - arr[i-1] > 1 && (
                    <span className="pagination-ellipsis">...</span>
                  )}
                  <button
                    onClick={() => handlePageChange(page)}
                    className={`pagination-btn ${currentPage === page ? 'active' : ''}`}
                  >
                    {page}
                  </button>
                </React.Fragment>
              ))
            }
            
            <button 
              onClick={() => handlePageChange(currentPage + 1)} 
              disabled={currentPage === totalPages}
              className="pagination-btn"
            >
              下一页
            </button>
            <button 
              onClick={() => handlePageChange(totalPages)} 
              disabled={currentPage === totalPages}
              className="pagination-btn"
            >
              末页
            </button>
            
            {/* 添加跳转到指定页面的输入框 */}
            <div className="jump-to-page">
              <span className="jump-label">跳转到:</span>
              <input
                type="number"
                min="1"
                max={totalPages}
                value={jumpPage}
                onChange={(e) => setJumpPage(e.target.value)}
                onKeyPress={handleJumpPageKeyPress}
                placeholder="页码"
                className="jump-input"
              />
              <button 
                onClick={handleJumpToPage}
                className="pagination-btn jump-btn"
              >
                跳转
              </button>
            </div>
          </div>
        )}

        {/* 悬停时显示封面图片 - 修改为居中且更大尺寸 */}
        
        {/* 视频播放器组件 */}
        <VideoPlayer 
          video={selectedVideo}
          onClose={handleClosePlayer}
        />

        {filteredVideos.length === 0 && !loading && (
          <div className="no-results">
            <h3>未找到视频</h3>
            <p>请调整搜索条件</p>
          </div>
        )}
      </div>
    </div>
    </div>
  );
};

export default VideoAdminPage;